/**
 * @Authors
 * Avinash Sridhar	G Number: G00861300
 * Martin Nguyen	G Number: G00396532
 * Jitin Krishnan	G Number: G00834757
 * 
 * @Course
 * CS571 Operating Systems Fall 2013
 * Assignment 3
 * Due: Dec 2, 2013 
 * Instructor: Hakan Aydin
 * 
 * Filename: ReconfigHandler.java
 * 
 **/

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;


public class ReconfigHandler extends Thread {

	private RMIServer mServer;
	
	private ServerSocket mReconfigServerSocketPort;	//going to be listening for potential reconfigs

	public InetAddress server_addr = InetAddress.getByName("localhost");
	
	public ReconfigHandler(RMIServer server) throws IOException
	{
		mServer = server;
		mReconfigServerSocketPort = new ServerSocket(mServer.getmCurrDeptModule().mTokenSocketPortNumber + 1);	//going to be listening for potential reconfigs
		System.out.println("Listening for reconfigs at port <" + mReconfigServerSocketPort.getLocalPort() + ">...");
	}

	@Override
	public void run() {
		while (true){
			try {
				 
				
				String value = ReadFromSocket(mReconfigServerSocketPort.accept());
				mServer.Reconfigure(value);

			}
			catch (IOException e) 
			{
				e.printStackTrace();
			}
		}
	}
	
	public String ReadFromSocket(Socket socket)
	{
		String socketValue = "";
		try {
			
			BufferedReader Reader = new BufferedReader( new InputStreamReader(socket.getInputStream()) );
			socketValue = Reader.readLine();
			
			socket.close();
			Reader.close();
			
		} catch (IOException e) 
		{
			//e.printStackTrace();
		}
		
		System.out.println(mServer.getmCurrDeptModule().mName + " got " + socketValue + " at " + System.currentTimeMillis());
		
		return socketValue;
	}
	
}
